<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select
          v-model="dateType"
          style="width: 170px; margin-right: 2px;"
        >
          <el-option label="创建时间" value="createTime" />
          <el-option label="出库时间" value="enterDt" />
        </el-select>
        <el-date-picker
          v-model="date"
          clearable
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item label="调出仓库:">
        <el-select
          v-model="query.storeId"
          placeholder="请选择"
          filterable
          clearable
        >
          <el-option
            v-for="item in leftStoreMap"
            :key="item.storeId"
            :label="item.storeName"
            :value="item.storeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item :table-form-merge="0.3">
        <el-button
          circle
          type="primary"
          @click="exchange"
        ><svg-icon
          class="map"
          icon-class="exchange"
        /></el-button>
      </el-form-item>

      <el-form-item label="调入仓库:">
        <el-select
          v-model="query.targetStoreId"
          placeholder="请选择"
          filterable
          clearable
        >
          <el-option
            v-for="item in rightStoreMap"
            :key="item.storeId"
            :label="item.storeName"
            :value="item.storeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="调拨车辆:">
        <el-select v-model="query.carNumber" placeholder="请选择" clearable>
          <el-option
            v-for="item in truckMap"
            :key="item.truckCode"
            :label="item.truckCode"
            :value="item.truckCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="司机:">
        <el-input v-model.trim="query.operator" clearable />
      </el-form-item>
      <el-form-item class="merge-item">
        <el-select v-model="qtype" style="width: 170px; margin-right: 2px;">
          <el-option value="stockOutCode" label="出库单号" />
          <el-option value="reBillCode" label="调拨单号" />
        </el-select>
        <el-input v-model.trim="txt" placeholder="请输入" clearable @keyup.enter.native="search" />
      </el-form-item>
      <el-form-item label="单据状态:">
        <el-select v-model="query.outBillStatus" placeholder="请选择" clearable>
          <el-option
            v-for="item in stockOutStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单据创建方式:">
        <el-select v-model="query.reBillType" placeholder="请选择" filterable clearable>
          <el-option
            v-for="item in stockReBillTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="出库类型:">
        <el-select v-model="query.reBillType" placeholder="请选择" filterable clearable>
          <el-option
            v-for="item in stockOutTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="[70303,1]" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button v-permission="[70303,2]" type="primary" icon="el-icon-plus" @click="add">新增</el-button>
        <el-button v-permission="[70303,4]" type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <addOutStorage ref="addOutStorage" :stock-out-type-map="stockOutTypeMap" :store-map="storeMap" :storage-store-map="storageStoreMap" :gd-status-map="gdStatusMap" :truck-map="truckMap" :driver-map="driverMap" @upDdataTable="upDataTable" />
    <outStorageDetail ref="outStorageDetail" :stock-out-type-map="stockOutTypeMap" :gd-status-map="gdStatusMap" />
    <stockTransDetail
      ref="stockTransDetail"
      :store-map="storeMap"
      :truck-map="truckMap"
      :driver-map="driverMap"
      :escort-map="escortMap"
      :trans-type-map="transTypeMap"
      :trans-status-map="transStatusMap"
      :stock-out-type-map="stockOutTypeMap"
      :stock-in-type-map="stockInTypeMap"
      :gd-status-map="gdStatusMap"
      @upDdataTable="upDataTable"
    />
  </div>
</template>

<script>
  import {
    queryMap,
    queryStockOutBillList,
    queryStockOutBillInvalid,
    stockTransWin,
    stockOutBillExport,
    queryExportDomain,
    confirmStockOutBill
  } from '@/api'
  import { formatColumnMap, parseTime } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { mapGetters } from 'vuex'
  import addOutStorage from '../components/addOutStorage.vue'
  import outStorageDetail from '../components/outStorageDetail.vue'
  import stockTransDetail from '../transferManage/components/stockTransDetail.vue'
  export default {
    name: 'outStorage',
    components: {
      addOutStorage,
      outStorageDetail,
      stockTransDetail
    },
    props: {
      storeMap: {
        type: Array,
        required: true
      },
      storageStoreMap: {
        type: Array,
        required: true
      },
      truckMap: {
        type: Array,
        required: true
      },
      driverMap: {
        type: Array,
        required: true
      },
      escortMap: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        actionColWidth: 80,
        leftStoreMap: [],
        rightStoreMap: [],
        dateType: 'createTime',
        date: [],
        qtype: '',
        txt: '',
        query: {
          outBillStatus: '',
          carNumber: '',
          storeId: '',
          targetStoreId: '',
          reBillType: '',
          operator: ''
        },
        stockOutTypeMap: [],
        stockInTypeMap: [],
        stockOutStatusMap: [],
        stockReBillTypeMap: [],
        gdStatusMap: [],
        transTypeMap: [{ desc: '内部充装调拨', value: 2 }, { desc: '内部调拨', value: 3 }],
        transStatusMap: [
          { value: -1, desc: '已作废', key: 'INVALID' },
          { value: 1, desc: '待审核', key: 'UNREVIEWED' },
          { value: 2, desc: '已审核', key: 'VALID' },
          { value: 4, desc: '已驳回', key: 'REJECT' },
          { value: 5, desc: '已出库', key: 'OUT' },
          { value: 6, desc: '已入库', key: 'IN' }
        ],
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ]),
      column: function() {
        return [
          {
            type: 'index'
          },
          // {
          //   prop: 'storeCode',
          //   label: '仓库编码'
          // },
          {
            prop: 'stockOutCode',
            width: 220,
            label: '单号',
            render: (h, { row }) => <el-link underline={false} onClick={() => this.openDetail(row)}>{row.stockOutCode}</el-link>
          },
          {
            prop: 'stockOutType',
            label: '出库类型',
            render: (h, { row }) => <span>{ row.stockOutType && formatColumnMap(this.stockOutTypeMap, 'value', row.stockOutType, 'desc') }</span>
          },
          {
            prop: 'createTime',
            label: '创建时间',
            width: 160,
            render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'storeName',
            label: '仓库(出 → 入)',
            width: 350,
            showOverflowTooltip: true,
            render: (h, { row }) => (
              <span>
                {row.storeName}&nbsp;→&nbsp;{row.targetStoreName}
              </span>
            )
          },
          {
            prop: 'carNumber',
            label: '调拨车辆'
          },
          {
            prop: 'operator',
            label: '司机'
          },
          {
            prop: 'reBillCode',
            width: 150,
            label: '关联调拨单',
            render: (h, { row }) => <el-link underline={false} onClick={() => this.stockCodeHandle(row)} >{row.reBillCode}</el-link>
          },
          {
            prop: 'enterDt',
            label: '出库时间',
            width: 160,
            render: (h, { row }) => <span>{ row.enterDt && parseTime(row.enterDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'outBillStatus',
            label: '状态',
            render: (h, { row }) => <span class={ row.outBillStatus === -1 ? 'dangerColor' : ''}>{ row.outBillStatus && formatColumnMap(this.stockOutStatusMap, 'value', row.outBillStatus, 'desc') }</span>
          },
          // {
          //   prop: 'createUser',
          //   label: '创建人'
          // },
          {
            label: '操作',
            align: 'center',
            fixed: 'right',
            className: 'action-col',
            width: this.actionColWidth,
            render: (h, { row, $index }) => {
              return (
                <div>
                  {row.outBillStatus === 1 && <el-link v-permission={[70303, 3]} underline={false} size='mini' type='danger' onClick={() => this.del(row, $index)}>
                    作废
                  </el-link>}
                  { row.outBillStatus === 1 && (<el-link v-permission={[70303, 5]} underline={false} size='mini' onClick={() => this.confirm(row, $index)}>
                  出库确认
                  </el-link>) }
                </div>
              )
              // { row.status !== -1 && <el-link v-permission='3' underline={false} size='mini' onClick={() => this.update(row, $index)}>
              //       编辑
              //     </el-link> }
            }
          }
        ]
      }
    },
    watch: {
      'storeMap': {
        handler(newVal, oldVal) {
          if (newVal.length) {
            this.leftStoreMap = this.storeMap
          }
        },
        deep: true,
        immediate: true
      },
      'storageStoreMap': {
        handler(newVal, oldVal) {
          if (newVal.length) {
            this.rightStoreMap = this.storageStoreMap
          }
        },
        deep: true,
        immediate: true
      }
    },
    async created() {
      this.getExportDomain()
      await Promise.all([this.getTimeFn(), this.queryOptionsMap()])
    },
    methods: {
      getTimeFn() {
        const end = new Date()
        const start = new Date()
        // start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
        this.date[0] = parseTime(start, '{y}-{m}-{d}') + ' 00:00:00'
        this.date[1] = parseTime(end, '{y}-{m}-{d}') + ' 23:59:59'
      },
      // 获取所属机构数据
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        if (this.date && this.date.length > 1) {
          query[`${this.dateType}`] = parseTime(this.date[0], '{y}-{m}-{d} {h}:{i}:{s}')
          query[`${this.dateType}End`] = parseTime(this.date[1], '{y}-{m}-{d} {h}:{i}:{s}')
        }
        if (this.qtype && this.txt) {
          query[this.qtype] = this.txt
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        const res = await queryStockOutBillList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res, res1, res2, res3, res4] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'StockOutType' }),
          mergeAsyncFunc(queryMap, { enumName: 'StockOutStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'StockReBillType' }),
          stockTransWin(),
          mergeAsyncFunc(queryMap, { enumName: 'StockInType' })
        ])
        this.stockOutTypeMap = res.data // 出库类型
        this.stockInTypeMap = res4.data // 入库类型
        this.stockOutStatusMap = res1.data // 出库状态
        this.stockReBillTypeMap = res2.data // 单据创建方式
        this.gdStatusMap = JSON.parse(res3.data.gdStatusMap) // 商品状态枚举
      },
      async add() {
        await this.$refs.addOutStorage.open()
      },
      // 出库单号
      async openDetail(row) {
        await this.$refs.outStorageDetail.open(row)
      },
      // 调拨单号
      stockCodeHandle(row) {
        this.$refs.stockTransDetail.open({ ...row, stockTransCode: row.reBillCode }, 'detail')
      },
      del(row, index) {
        this.$confirm('确定要作废该出库单？', '提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$message({
            message: '正在作废',
            duration: 0,
            iconClass: 'el-icon-loading'
          })
          queryStockOutBillInvalid({ stockOutCode: row.stockOutCode }).then(() => {
            this.$notify({
              title: '提示',
              message: '作废成功',
              type: 'success',
              duration: 2000
            })
            this.upDataTable()
          }).finally(() => {
            loading.close()
          })
        })
      },
      exchange() {
        if (this.query.storeId && this.query.targetStoreId) {
          const num1 = this.query.storeId
          const num2 = this.query.targetStoreId
          this.query.storeId = num2
          this.query.targetStoreId = num1
          const array1 = JSON.parse(JSON.stringify(this.rightStoreMap))
          const array2 = JSON.parse(JSON.stringify(this.leftStoreMap))
          this.rightStoreMap = JSON.parse(JSON.stringify(array2))
          this.leftStoreMap = JSON.parse(JSON.stringify(array1))
        }
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 更新数据
      upDataTable() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain)
          .then((res) => {
            this.exportDomain = res.data
          })
      },
      // 导出
      async exportFile() {
        this.$confirm('确定导出数据？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          var list = JSON.parse(JSON.stringify(this.column))
          list.pop()
          list.shift()
          const value = {}
          await list.forEach(l => {
            value[l.prop] = l.label
            return value
          })
          const params = {
            ...this._getQuery(this.query)
          }
          const query = {
            paramInfo: params,
            kv: value
          }
          await stockOutBillExport(query).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      confirm(row) {
        this.$confirm('是否确认出库？', '提示', {
          type: 'warning'
        }).then(() => {
          confirmStockOutBill({ stockOutCode: row.stockOutCode }).then(() => {
            this.$notify({
              title: '提示',
              message: '出库成功',
              type: 'success',
              duration: 2000
            })
            this.upDataTable()
          }).finally(() => {
          })
        })
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach(it => {
                width += (it.offsetWidth + 10)
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      reset() {
        this.$refs.form.resetFields()
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;
}
</style>
